<?php

namespace App\Http\Controllers\Property;

use App\Common\sms;
use App\Common\SmsClient;
use App\Common\json;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Payment\Common\PayException;
use Payment\Client\Charge;
use Payment\Config;
use Payment\Client\Notify;
//use Payment\TestNotify;

class CsController extends  Controller {
    private    $sms_url 		= "http://api.zthysms.com/sendSmsBatchIdentity.do";//提交地址
    private    $username 	    = "nbsqyl2017hy";//用户名
    private    $password 	    = "ZTnbsqyl20178520";//原密码

    public function smsorder($id)
    {
            $sms = new SmsClient($this->sms_url, $this->username, $this->password);
            $order = DB::table('order')
                ->leftjoin('goods', 'order.order_goods_id', '=', 'goods.goods_id')
                ->leftjoin('user', 'order.user_order', '=', 'user.user_id')
                ->leftjoin('address', 'order.order_address', '=', 'address.address_id')
                ->leftjoin('goodstype', 'goods.type_goods', '=', 'goodstype.type_id')
                ->leftjoin('admin', 'goods.goods_admin', '=', 'admin.admin_id')
                ->where('order', $id)->first();
            $address = $order->province . $order->address;
            $rand = "http://www.mukitech.com/wuye/app/public/property/order/$id";
            $datas = array(
                'content' => "您好，您有新的栖云里订单！您的订单详情：收件人：{$order->real_name}；收货地址：$address;一共订购了{$order ->quantity}件物品，明细如下；  商品名称：{$order ->order_goodsname};商品分类:{$order ->typename};付款总金额为¥{$order->sum}元。【栖云里】※ 亲爱的小主，非常高兴您在栖云里订购商品! 您的订单详情：:您一共订购了{$order ->quantity}件物品，明细如下：商品名称：{$order ->order_goodsname};商品分类:{$order ->typename} ;付款总金额为¥{$order->sum}元;订单详情入口:$rand;
                如果没有问题，我们将尽快为您安排，谢谢！【栖云里】",//短信内容
                'mobile' => "$order->admin_phone,$order->phone",//手机号码
                'productid' => '887361',//产品id
                'xh' => ''//小号
            );
            $sms->data = $datas;
            $value = $sms->sendSMS('post');
            return $value;
    }

    public function paycs(Request $request)
    {
        if ($request->isMethod('post')) {
            $aliConfig = [
                'use_sandbox'               => false,// 是否使用沙盒模式
                'partner'                   => '2088721065202522',
                'app_id'                    => '2017052507339343',
                'sign_type'                 => 'RSA2',// RSA  RSA2

                // 可以填写文件路径，或者密钥字符串  当前字符串是 rsa2 的支付宝公钥(开放平台获取)
                'ali_public_key'            => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmCrN9DnpHiQ7N8BJSCtKURvYJRKqbaCJwwhuXaayxgkvJ5TUyjJsJpOckSA1BJLmZRlz4HlwJrrFTIwS9pRxpPAeTFys6MwUTXgC5efmjT+3mGDrWsq6yjzfgtA0vr4N/zze7SnhVPI9aihtS55zt+twOpp3qwTkcA+a8P2+B9Lq/jFqDeM9qLTS9ZzGSrdO58G5t/hjNmmQycP7rhZCWTp4NK4gbRWjqw2g128coZJJlWc/M71E6jEQ5suw6dbC2596/TKOikYyzD52Et8PVp7axo/LG2zIr3fT7/5FIEfDi4pd3/NW8IvsAEipbuEuMNUJxUXwgDZqmjTvfK77RwIDAQAB',

                // 可以填写文件路径，或者密钥字符串  我的沙箱模式，rsa与rsa2的私钥相同，为了方便测试
                'rsa_private_key'           =>'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCk/SWK+rivKCiRrMkFYG2rR0YicVDzrpgGdYA9KKpUD8t94K1m4oCVT1R9eu53Jq5YmNzFCqFQooMcA0OvB4iVzpJMmSVUGQolFL5VnEkxhLk2zHTm35snCQYjrqiXjl2wwM7GvAzvBivRgbPoTUCJ+nbW0ybGM+85nSlbgJSNGcAgo8Pmr/cGgmbwQcmsNVtipgpraL2blI3qhLeYH10G0oz9kCM1xU5FF4ZgDVetbKDfzI0t3TEvVu9r/lbUp08XWgEp4c7defxRca69CZBWJrftEMpPDDLQws+zh6uVjWxzxEdMNypvIQEogF++zpFiEvXEYain/hugtoJ7I/yLAgMBAAECggEADyhmu5b/QrBY0dFjAohyaur4aY+plUm0E9vVtUi4JVLyKhVrOOmUUKNiKskRgYbfO6qHld69JV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iF7VrvR3Xd6FweITW2m+VklPh6ndmAJEsc+izlJHKJUReT2kE/k6P7c9VmISGixQA==',
                // 与业务相关参数
                'notify_url'                => 'http://www.mukitech.com/wuye/app/public/property/PaySuccess',
                //'return_url'                => 'http://www.mukitech.com/wuye/app/public/property/PaySuccess',

                'return_raw'                => true,// 在处理回调时，是否直接返回原始数据，默认为 true
            ];
            $orderNo = $request ->input('order');
            $select  = DB::table('order')
                     ->leftjoin('user','order.user_order','=','user.user_id')
                     ->where('order',$orderNo)
                      ->first();

            $payData = [
                'body'    => 'ali qr pay',
                'subject'    => $select ->order_goodsname,
                'order_no'    => $orderNo,
                'timeout_express' => time() + 600,// 表示必须 600s 内付款
                'amount'    => '0.01',// 单位为元 ,最小为0.01
                'return_param' => '123123',
                'client_ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',// 客户地址
                'goods_type' => '1',
                'store_id' => '',
            ];
            try {
                $str = Charge::run(Config::ALI_CHANNEL_APP, $aliConfig, $payData);
            } catch (PayException $e) {
                echo $e->errorMessage();
                exit;
            }
            $dd  = array('value'=>$str);
            return json::json('success', '获取订单数据库成功', $dd);


        }
    }

    public function PaySuccess(Request $request){
        if($request ->isMethod('post')){
           // $callback = new
            $aliConfig = [
                'use_sandbox'               => false,// 是否使用沙盒模式
                'partner'                   => '2088721065202522',
                'app_id'                    => '2017052507339343',
                'sign_type'                 => 'RSA2',// RSA  RSA2

                // 可以填写文件路径，或者密钥字符串  当前字符串是 rsa2 的支付宝公钥(开放平台获取)
                'ali_public_key'            => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmCrN9DnpHiQ7N8BJSCtKURvYJRKqbaCJwwhuXaayxgkvJ5TUyjJsJpOckSA1BJLmZRlz4HlwJrrFTIwS9pRxpPAeTFys6MwUTXgC5efmjT+3mGDrWsq6yjzfgtA0vr4N/zze7SnhVPI9aihtS55zt+twOpp3qwTkcA+a8P2+B9Lq/jFqDeM9qLTS9ZzGSrdO58G5t/hjNmmQycP7rhZCWTp4NK4gbRWjqw2g128coZJJlWc/M71E6jEQ5suw6dbC2596/TKOikYyzD52Et8PVp7axo/LG2zIr3fT7/5FIEfDi4pd3/NW8IvsAEipbuEuMNUJxUXwgDZqmjTvfK77RwIDAQAB',

                // 可以填写文件路径，或者密钥字符串  我的沙箱模式，rsa与rsa2的私钥相同，为了方便测试
                'rsa_private_key'           =>'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCk/SWK+rivKCiRrMkFYG2rR0YicVDzrpgGdYA9KKpUD8t94K1m4oCVT1R9eu53Jq5YmNzFCqFQooMcA0OvB4iVzpJMmSVUGQolFL5VnEkxhLk2zHTm35snCQYjrqiXjl2wwM7GvAzvBivRgbPoTUCJ+nbW0ybGM+85nSlbgJSNGcAgo8Pmr/cGgmbwQcmsNVtipgpraL2blI3qhLeYH10G0oz9kCM1xU5FF4ZgDVetbKDfzI0t3TEvVu9r/lbUp08XWgEp4c7defxRca69CZBWJrftEMpPDDLQws+zh6uVjWxzxEdMNypvIQEogF++zpFiEvXEYain/hugtoJ7I/yLAgMBAAECggEADyhmu5b/QrBY0dFjAohyaur4aY+plUm0E9vVtUi4JVLyKhVrOOmUUKNiKskRgYbfO6qHld69JVBY5UjzffAeP00kKb9kK47FXNTEC8949gCwl3U/RDrE4Vg15S9Vs97TgrqkBKQgOBGEExJseeonBMYrBt+NT2ZUEyH6O7rbav8NHXb00L70fNnFxc7LxSEyEAgPXx/5qDJW3lgJYxQJRd5PSk7p0jgc6uiTLdjQDKIgoyNcX4rgCH3XVrSI7LVFjL+j3y2ra/ZQkCCfi4xTlabOkTfblyOZH+QtomkmdfidZTLfJ3LZqVlstgLeMgYMQj/55sX5/iZfas4+TMlZ2QKBgQD7RDbMJDnUQhViTU4fm8bVEDlNPJzrmrNRUTrAXNKVLsHFCfiDFZvzIykfZ7RUvaqhB4QMu8eU62eGPKcYO5ECitZSzBGd5vbjeXIT4EY8FKMX0RyTQz1GaGM/hWKNhPtRtM5vVw3doU5jfldGphIwLV8ZznFN+4XY8+UUdJMiZQKBgQCoGNcqXld4cvNZGEbjw5p64AEGLZdHDDt08ssE1RyM6xa6EH7qyAZbpFAE/bSOi9VVYSX0m8irz7JcyfvN6lSTo0u+Z0WOuv+RJoVhSTBhvClZyJnUiErk8j7t/fs+KRmtpy52XZXCJRDRIqGrfX4qAUnbFBbXwYAlCFS4bj08LwKBgEox4lx1df4PZXEZkrASt6vClqkP9OY9UCX67nZO8n/Kxr0ALLnIb7xj7YiwfrdnKjNSnNOFv3Fh8bfZwR2OuUse5Bqe17TgtpaFDgKAfzzOezpVLTLu7/EScfwXzvorAmsmEK8f7aA8OYF3lR3ve/9t5l8gbqSwWN2vZz2bDrdhAoGAR54dvg1n0weWqnTvbwbdgFCD3y/5benGQzNWT/7EJT3b9vYkPL9wBgdhmF7HWJw3DiNP2oGs45af9WyQ/dBCrIw8Lykst3zwedUhqqtWE63pKDmRYL2YuyaCrT8yle9I43WBFCkXLxo/qfrJSpky8Y6O+un6OX5VrHF6NwGw0T0CgYAllYiZrBonvLCx33uEshjgd9Kt8gwHY56DhF4NPqZaozCMId86G+DghglB6H7MjjgYY9zkRZ+W06stKOZXQaKEUOc2jSJmfoZI2LNBGcOjiiF7VrvR3Xd6FweITW2m+VklPh6ndmAJEsc+izlJHKJUReT2kE/k6P7c9VmISGixQA==',
                // 与业务相关参数
                'notify_url'                => 'http://www.mukitech.com/wuye/app/public/property/PaySuccess',
                //'return_url'                => 'http://www.mukitech.com/wuye/app/public/property/PaySuccess',

                'return_raw'                => true,// 在处理回调时，是否直接返回原始数据，默认为 true
            ];
            $type = 'ali_charge';// ali_charge wx_charge  cmb_charge

            try {
                // 获取第三方的原始数据，未进行签名检查，根据自己需要决定是否需要该步骤
                $retData = Notify::getNotifyData($type, $aliConfig);

                // $ret = Notify::run($type, $aliConfig, $callback);// 处理回调，内部进行了签名检查
                // $dd = $retData['trade_status'];
                if($retData) {
                    $out_trade_no = $_POST['out_trade_no'];

                    //支付宝交易号

                    $trade_no = $_POST['trade_no'];

                    //交易状态
                    $trade_status = $_POST['trade_status'];
                    //  $value = $retData['out_trade_no'];
                    if($_POST['trade_status'] == 'TRADE_FINISHED') {

                    }
                    elseif ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                        $order =DB::table('order')->where('order', $out_trade_no)->update(['order_status' => 0]);
                        if($order == true) {
                            $data = DB::table('order')->where('order', $out_trade_no)->first();
                            $id = explode(',', $data->order_goodsname);
                            $userid = $data->user_order;
                            foreach ($id as $k => $v) {
                                DB::table('strata_fee')->where('years', '=', $v)->where('user_stratafee', $userid)->update(['state' => 1]);
                            }

                            $ids = explode(';', $data->order_goodsname);
                            foreach ($ids as $v => $k) {
                                DB::table('parking_fees')->where('user_parkingfees', $userid)->where('parking_set', $k)
                                    ->update(['parking_state' => 1]);
                            }
                            if ($data->order_type == 2) {
                                $dataone = DB::table('order')->where('order', $out_trade_no)->where('order_type', 2)->first();
                                $userdata = DB::table('user')->where('user_id', $dataone->user_order)->first();
                                $sum = DB::table('village')->where('village_id', $userdata->user_village)->first();
                                $datasum = $sum->village_wallet + $dataone->sum;
                                DB::table('village')->where('village_id', $userdata->user_village)->update(['village_wallet' => $datasum]);
                            } elseif ($data->order_type == 3) {
                                $datatwo = DB::table('order')->where('order', $out_trade_no)->where('order_type', 3)->first();
                                $userdatatwo = DB::table('user')->where('user_id', $datatwo->user_order)->first();
                                $sumtwo = DB::table('village')->where('village_id', $userdatatwo->user_village)->first();
                                $datasumtwo = $sumtwo->village_wallet + $datatwo->sum;
                                DB::table('village')->where('village_id', $userdatatwo->user_village)->update(['village_wallet' => $datasumtwo]);
                            }
                            $sms   = $this ->smsorder($out_trade_no);
                            Log::info($sms);
                        }else{
                            DB::table('record') ->where('recordorder',$out_trade_no)->update(['option'=>1]);
                            $select = DB::table('record')->where('recordorder', $retData['out_trade_no'])->first();
                            $datas = DB::table('user')->where('user_id', $select->record_user)->first();
                            $money = $datas->usermoney + $select->record_money;
                            DB::table('user')->where('user_id', $select->record_user)->update(['usermoney' => $money]);
                        }
                    }
                    echo "success";		//请不要修改或删除
                }else{
                    echo "fail";	//请不要修改或删除
                }

            } catch (PayException $e) {
                echo $e->errorMessage();
                exit;
            }

            // return $ret;
        }

    }

    public function paywx(Request $request){
        if($request ->isMethod('post')){
            $wxConfig = [
                'use_sandbox'       => false,// 是否使用 微信支付仿真测试系统
                'app_id'            => 'wx58f7d9a1d1591311',  // 公众账号ID
                'mch_id'            => '1487628602',// 商户id
                'md5_key'           => 'raS7PylXxB7ENHL7loeepRZJryaCds2c',// md5 秘钥
                //'APPSECRET'         => 'd6bd2356c104deb1e97d6d12b9a5417f',
                'app_cert_pem'      => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR .  'pem' . DIRECTORY_SEPARATOR . 'weixin_app_cert.pem',
                'app_key_pem'       => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR .  'pem' . DIRECTORY_SEPARATOR . 'weixin_app_key.pem',
                'sign_type'         => 'MD5',// MD5  HMAC-SHA256
                'limit_pay'         => [
                    //'no_credit',
                ],// 指定不能使用信用卡支付   不传入，则均可使用
                'fee_type'          => 'CNY',// 货币类型  当前仅支持该字段

                'notify_url'        => 'http://www.mukitech.com/wuye/app/public/property/wxpay',

                'redirect_url'      => '',// 如果是h5支付，可以设置该值，返回到指定页面

                'return_raw'        => false,// 在处理回调时，是否直接返回原始数据，默认为true
            ];
            $orderNo = $request ->input('order');

            $payData = [
                'body'    => 'test body',
                'subject'    => 'test subject',
                'order_no'    => $orderNo,
                'timeout_express' => time() + 600,// 表示必须 600s 内付款
                'amount'    => '0.01',// 微信沙箱模式，需要金额固定为3.01
                'return_param' => '123',
                'client_ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',// 客户地址
            ];

            try {
                $ret = Charge::run(Config::WX_CHANNEL_APP, $wxConfig, $payData);
            } catch (PayException $e) {
                echo $e->errorMessage();
                exit;
            }
          //  $dd = array('value' => $ret);
            return json::json('success', '获取支付数据成功', $ret);
        }
    }

    public function wxpay(Request $request){
        if($request ->isMethod('post')){
            $wxConfig = [
                'use_sandbox' => false,// 是否使用 微信支付仿真测试系统
                'app_id' => 'wx58f7d9a1d1591311',  // 公众账号ID
                'mch_id' => '1487628602',// 商户id
                'md5_key' => 'raS7PylXxB7ENHL7loeepRZJryaCds2c',// md5 秘钥
                //'APPSECRET'         => 'd6bd2356c104deb1e97d6d12b9a5417f',
                'app_cert_pem' => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR . 'pem' . DIRECTORY_SEPARATOR . 'weixin_app_cert.pem',
                'app_key_pem' => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR . 'pem' . DIRECTORY_SEPARATOR . 'weixin_app_key.pem',
                'sign_type' => 'MD5',// MD5  HMAC-SHA256
                'limit_pay' => [
                    //'no_credit',
                ],// 指定不能使用信用卡支付   不传入，则均可使用
                'fee_type' => 'CNY',// 货币类型  当前仅支持该字段

                'notify_url' => 'http://www.mukitech.com/wuye/app/public/property/wxsuccess',

                'redirect_url' => '',// 如果是h5支付，可以设置该值，返回到指定页面

                'return_raw' => false,// 在处理回调时，是否直接返回原始数据，默认为true
            ];
            $type = 'wx_charge';// ali_charge wx_charge  cmb_charge
            try {
                // 获取第三方的原始数据，未进行签名检查，根据自己需要决定是否需要该步骤
                $retData = Notify::getNotifyData($type, $wxConfig);
                // $ret = Notify::run($type, $aliConfig, $callback);// 处理回调，内部进行了签名检查
                // $dd = $retData['trade_status'];
                if($retData) {
                    if ($retData['result_code'] == 'SUCCESS') {
                        $out_trade_no = $retData['out_trade_no'];
                       $order =DB::table('order')->where('order', $out_trade_no)->update(['order_status' => 0]);
                        if($order == true) {
                            $data = DB::table('order')->where('order', $out_trade_no)->first();
                            $id = explode(',', $data->order_goodsname);
                            $userid = $data->user_order;
                            foreach ($id as $k => $v) {
                                DB::table('strata_fee')->where('years', '=', $v)->where('user_stratafee', $userid)->update(['state' => 1]);
                            }

                            $ids = explode(';', $data->order_goodsname);
                            foreach ($ids as $v => $k) {
                                DB::table('parking_fees')->where('user_parkingfees', $userid)->where('parking_set', $k)
                                    ->update(['parking_state' => 1]);
                            }
                            if ($data->order_type == 2) {
                                $dataone = DB::table('order')->where('order', $out_trade_no)->where('order_type', 2)->first();
                                $userdata = DB::table('user')->where('user_id', $dataone->user_order)->first();
                                $sum = DB::table('village')->where('village_id', $userdata->user_village)->first();
                                $datasum = $sum->village_wallet + $dataone->sum;
                                DB::table('village')->where('village_id', $userdata->user_village)->update(['village_wallet' => $datasum]);
                            } elseif ($data->order_type == 3) {
                                $datatwo = DB::table('order')->where('order', $out_trade_no)->where('order_type', 3)->first();
                                $userdatatwo = DB::table('user')->where('user_id', $datatwo->user_order)->first();
                                $sumtwo = DB::table('village')->where('village_id', $userdatatwo->user_village)->first();
                                $datasumtwo = $sumtwo->village_wallet + $datatwo->sum;
                                DB::table('village')->where('village_id', $userdatatwo->user_village)->update(['village_wallet' => $datasumtwo]);
                            }
                            $sms   = $this ->smsorder($out_trade_no);
                            Log::info($sms);
                        }else{
                            DB::table('record') ->where('recordorder',$out_trade_no)->update(['option'=>1]);
                            $select = DB::table('record')->where('recordorder', $retData['out_trade_no'])->first();
                            $datas = DB::table('user')->where('user_id', $select->record_user)->first();
                            $money = $datas->usermoney + $select->record_money;
                            DB::table('user')->where('user_id', $select->record_user)->update(['usermoney' => $money]);
                        }
                    }

                    echo "success";		//请不要修改或删除
                }else{
                    echo "fail";	//请不要修改或删除
                }


            } catch (PayException $e) {
                echo $e->errorMessage();
                exit;
            }
        }
    }

    public function balancepay(Request $request){
        if($request ->isMethod('post')){
            $orderNo = $request ->input('order');
        }

    }





}